package com.homework.ch02;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/11/6
 * @Description:
 */
public class Test01 {
    private static String driverClass = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/briup";
    private static String username = "briup";
    private static String password = "briup";
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        BufferedReader br = null;
        try {
            // 加载驱动程序
            Class.forName(driverClass);
            // 获取数据库连接
            conn = DriverManager.getConnection(url, username, password);
            conn.setAutoCommit(false);
            // 读取数据
            String sql = "insert into t_customer(id,name, age, birthday) values(?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            br = new BufferedReader(new InputStreamReader(new FileInputStream("3-jdbc-demo/src/customer.txt")));

            String line = null;
            while ((line = br.readLine())!= null) {
                String[] date = line.split(":");
                pstmt.setInt(1, Integer.parseInt(date[0]));
                pstmt.setString(2, date[1]);
                pstmt.setInt(3, Integer.parseInt(date[2]));
                pstmt.setString(4, date[3]);
                pstmt.executeUpdate();
            }
            conn.commit();
            System.out.println("数据插入成功！");
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
                System.out.println("数据插入失败，事务回滚");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
